﻿using System;
using System.Linq;
using LINQtoFxCop.Core;
using Microsoft.FxCop.Sdk;

namespace LINQtoFxCop.Flaws.Design
{
  internal static class DesignExtenders
  {
    private delegate bool IsWantedMethod(Method method);

    public static bool OverridesEquals(this ClassNode @class)
    {
      return OverridesMethod(@class, IsEqualsMethod);
    }
    public static bool OverridesGetHashCode(this ClassNode @class)
    {
      return OverridesMethod(@class, IsGetHashCodeMethod);
    }
    public static bool HasPublicConstructor(this TypeNode type)
    {
      return type.Members.OfType<InstanceInitializer>().HasItemWhen(ctor => ctor.IsPublic);
    }

    private static bool OverridesMethod(TypeNode @class, IsWantedMethod isWantedMethod)
    {
      return
        (
          from method in @class.Members.OfType<Method>()
          where method.OverridesBaseClassMember && isWantedMethod(method)
          select method
        ).HasItem();
    }

    private static bool IsEqualsMethod(Method method)
    {
      if (!method.Name.Name.Equals("Equals", StringComparison.Ordinal))
        return false;

      if (method.Parameters.Count != 1)
        return false;

      if (method.Parameters[0].Type != FrameworkTypes.Object)
        return false;

      return true;
    }
    private static bool IsGetHashCodeMethod(Method method)
    {
      if (!method.Name.Name.Equals("GetHashCode", StringComparison.Ordinal))
        return false;

      if (method.Parameters.Count != 0)
        return false;

      return true;
    }
  }
}